<template>
    <div>
        <div style="position: absolute;top:7px;z-index: 99;padding: 5px;display: flex">
            <el-select v-model="value" @change="Rendering" filterable placeholder="请选择" @clear="clear" clearable>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>

            <el-upload style="padding-left: 10px" class="upload-demo" action="#" ref="upload" :show-file-list="false"
                       :http-request="handleFileUpload">
                <el-button class="el-icon-upload" type="success">文件上传</el-button>
            </el-upload>
            <el-button style="margin-left: 5px" type="primary" @click="upSheet">保存当前页</el-button>
<!--            <el-button style="margin-left: 5px" @click="upWork">保存工作薄</el-button>-->
            <!--<el-button style="margin-left: 5px" type="warning" @click="exportFile">导出excel</el-button>-->
        </div>
        <div style="position: absolute;top:7px;right: 5px; z-index: 99;padding: 5px;display: flex">
            <el-button-group>
                <el-button style="margin-left: 5px" type="primary" @click="getTableDataToLucksheet">同步表数据</el-button>
                <el-button type="primary" icon="el-icon-edit" @click="openTables"></el-button>
            </el-button-group>
            <el-button-group>
                <el-button style="margin-left: 5px" type="warning" @click="feedback">数据上传</el-button>
                <el-button type="warning" icon="el-icon-edit" @click="openUpload"></el-button>
            </el-button-group>
<!--            <el-button style="margin-left: 5px" type="warning" @click="ceshi">测试</el-button>-->
        </div>
        <el-dialog title="配置数据来源" :visible.sync="dialog1" width="70%" :before-close="handleClose1">
            <el-tooltip style="margin-left: 20px"
                        placement="right-start">
                <div slot="content">自定义SQL模式，需要注意SQL的写法，id字段一定要有<br/>
                    left join等关联语句，需要考虑数据上传时上传到哪张表，将这张表的id作为id返回<br/>
                    其他表id起别名，所有字段别名不可重复，否则会影响数据上传<br/>
                    示例：<br/>
                    select pos.id,pos.staff_code as 员工号,pcc.name as 公司名称
                    from mes.puc_oa_staff pos
                    left join mes.puc_com_company pcc on pos.company_id = pcc.id
                    order by pos.id desc
                    limit 10
                </div>
                <i class="el-icon-info" style="font-size: 16px;"></i>
            </el-tooltip>
            <el-form ref="form1" label-width="100px">
                <el-form-item label="操作类型:">
                    <el-select v-model="operateType" filterable placeholder="请选择操作类型" style="width:100%">
                        <el-option v-for="item in operateTypeList" :key="item.value" :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <div v-if="this.operateType === 1">
                    <el-form-item label="选择库:">
                        <el-select v-model="dbName" @change="getTables(dbName)" filterable placeholder="请选择选择库"
                                   style="width:100%">
                            <el-option v-for="item in dbList" :key="item.label" :label="item.label" :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择表:">
                        <el-select v-model="tableName" filterable placeholder="请选择数据表" style="width:100%">
                            <el-option v-for="item in tableList" :key="item.label" :label="item.label"
                                       :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据类型:">
                        <el-select v-model="tableType" filterable placeholder="请选择操作类型" style="width:100%">
                            <el-option v-for="item in dowType" :key="item.value" :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据条数:">
                        <el-input v-model="limit"></el-input>
                    </el-form-item>
                </div>
                <div v-if="this.operateType === 2">
                    <el-form-item label="字段顺序:">
                        <el-input pagination="输入字段顺序" style="white-space: pre-wrap" v-model="fieldOrder"></el-input>
                    </el-form-item>
                    <el-form-item label="自定义SQL:">
                        <el-input pagination="输入SQL" style="white-space: pre-wrap"
                                  :autosize="{ minRows: 8, maxRows: 12}"
                                  type="textarea" v-model="dowSql"></el-input>
                    </el-form-item>
                </div>
                <div v-if="this.operateType === 3">
                    <el-form-item label="请求类型:">
                        <el-select v-model="method" filterable placeholder="请选择请求类型" style="width:100%">
                            <el-option v-for="item in methodType" :key="item.value" :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="请求地址">
                        <el-input placeholder="请求地址填写域名后面的地址即可,会自动拼接域名或服务器地址" style="white-space: pre-wrap"
                                  v-model="apiUrl"></el-input>
                    </el-form-item>
                </div>
            </el-form>

            <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose1">取 消</el-button>
        <el-button type="primary" @click="upDialog1">确 定</el-button>
      </span>
        </el-dialog>

        <el-dialog title="配置上传模式" :visible.sync="dialog2" width="70%" :before-close="handleClose2">
            <el-form ref="form2" label-width="100px">
                <el-row>
                    <el-col :span="22">
                        <el-form-item label="上传字段:">
                            <el-select v-model="filds" filterable multiple placeholder="请选择上传字段" style="width:100%">
                                <el-option v-for="item in fildList" :key="item.label" :label="item.label"
                                           :value="item.label">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-button style="margin-left: 5px" type="primary" @click="setAll">全选</el-button>
                    </el-col>
                </el-row>
                <el-form-item label="操作类型:">
                    <el-select v-model="uploadType" @change="setTmpName" filterable placeholder="请选择操作类型"
                               style="width:100%">
                        <el-option v-for="item in uploadTypeList" :key="item.value" :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="临时表名称" v-if="this.uploadType === 2">
                    <el-input readonly="" style="white-space: pre-wrap" v-model="tmpName"></el-input>
                </el-form-item>
                <el-form-item label="选择库:" v-if="this.uploadType === 1">
                    <el-select v-model="uploadDb" @change="getTables(uploadDb)" filterable placeholder="请选择选择库"
                               style="width:100%">
                        <el-option v-for="item in dbList" :key="item.label" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上传表:" v-if="this.uploadType === 1">
                    <el-select v-model="uploadTb" filterable placeholder="请选择数据表" style="width:100%">
                        <el-option v-for="item in tableList" :key="item.label" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <div v-if="this.uploadType === 3">
                    <el-form-item label="请求类型:">
                        <el-select v-model="uploadApiMethod" filterable placeholder="请选择请求类型" style="width:100%">
                            <el-option v-for="item in methodType" :key="item.value" :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="请求地址">
                        <el-input placeholder="请求地址填写域名后面的地址即可,会自动拼接域名或服务器地址" style="white-space: pre-wrap"
                                  v-model="uploadApiUrl"></el-input>
                    </el-form-item>
                </div>

                <el-form-item label="样式额外存储:">
                    <el-switch v-model="styleSwitch" active-value="1"
                               inactive-value="-1">
                    </el-switch>
                </el-form-item>

                <el-row v-if="styleSwitch === '1'">
                    <el-col :span="6">
                        <div class="grid-content bg-purple">
                            <el-form-item label="选择库:">
                                <el-select v-model="styleDb" @change="getTables(uploadDb)" filterable
                                           placeholder="请选择选择库"
                                           style="width:100%">
                                    <el-option v-for="item in dbList" :key="item.label" :label="item.label"
                                               :value="item.label">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="grid-content bg-purple-light">
                            <el-form-item label="选择表:">
                                <el-select v-model="styleTable" @change="getFieldsByTable()" filterable
                                           placeholder="请选择数据表" style="width:100%">
                                    <el-option v-for="item in tableList" :key="item.label" :label="item.label"
                                               :value="item.label">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="grid-content bg-purple">
                            <el-form-item label="关联字段:">
                                <el-select v-model="relateField" filterable placeholder="请选择字段" style="width:100%">
                                    <el-option v-for="item in styleFields" :key="item.label" :label="item.label"
                                               :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="grid-content bg-purple-light">
                            <el-form-item label="关联参数:">
                                <el-select v-model="relateQuery" filterable placeholder="请选择参数" style="width:100%">
                                    <el-option v-for="item in queryList" :key="item.value" :label="item.label"
                                               :value="item.label">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </el-col>
                </el-row>

                <el-form-item label="自定义SQL:" v-if="this.uploadType !== 3">
                    <el-input pagination="输入SQL" style="white-space: pre-wrap" :autosize="{ minRows: 8, maxRows: 12}"
                              type="textarea" v-model="uploadSql"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">取 消</el-button>
        <el-button type="primary" @click="feedback">确 定</el-button>
      </span>
        </el-dialog>

        <div id="luckysheet"
             style="margin:0px;padding:0px;position:absolute;width:100%;height:100%;left: 0px;top: 0px;bottom:0px;">
        </div>
    </div>
</template>
<script>
    import Vue from 'vue'
    // 在 main.js 或组件内引入
    import jQuery from 'jquery';
    // 引入 spectrum 插件
    import 'spectrum-colorpicker';
    import 'jquery-mousewheel';
    import luckysheet from 'luckysheet';
    import luckyexcel from 'luckyexcel';
    // import axios from "axios";
    // import {exportExcel} from './export'
    // element-ui
    import {
        Button,
        ButtonGroup,
        Dialog,
        Form,
        FormItem,
        Input,
        Message,
        Option,
        Select,
        Tooltip,
        Upload,
        Switch,
        Row,
        Col,
    } from 'element-ui';
    // js
    import {
        dataFeedback,
        dataToDataByComment,
        dataToLucksheetModel1,
        datatoLucksheetModel2,
        formatDate,
        getLocalHostDB,
        getOnlineFileItem,
        getOnlineFileItemByid,
        getOptions,
        getTableDataByType1,
        getTableDataByType2,
        getTableList,
        lucksheetToDataModelOne,
        lucksheetToDataModelTwo,
        saveFile,
        upSheetOne,
        upWorkTotal,
        luckysheetToDataModelThree,
        sqlFeedback,
        getDataById,
        saveStyleByQuery,
        getStyleByQuery,
        getDataByApiUrl,
        uploadByApi
    } from "./index";

    window.jQuery = jQuery;
    window.$ = jQuery;

    Vue.prototype.$message = Message;
    Vue.component('el-select', Select);
    Vue.component('el-option', Option);
    Vue.component('el-upload', Upload);
    Vue.component('el-button', Button);
    Vue.component('el-button-group', ButtonGroup);
    Vue.component('el-dialog', Dialog);
    Vue.component('el-form', Form);
    Vue.component('el-form-item', FormItem);
    Vue.component('el-input', Input);
    Vue.component('el-tooltip', Tooltip);
    Vue.component('el-switch', Switch);
    Vue.component('el-row', Row);
    Vue.component('el-col', Col);
    export default {
        name: "index",
        data() {
            return {
                // 数据同步的弹窗
                dialog1: false,
                // 数据上传的弹窗
                dialog2: false,
                // 当前登录用户
                staffCode: "80022",
                // luckysheet的默认数据结构
                option: {
                    container: 'luckysheet',
                    lang: 'zh',
                    plugins: ['chart'],
                    showsheetbar: true,
                    allowUpdate: true,
                    showinfobar: true,
                    showsheetbarConfig: { // sheet页管理
                        add: true,
                        menu: false
                    },
                    data: [],
                    title: "",
                },
                // online_file的文件数组
                options: [],
                // 选中的文件ID
                value: '',
                // 表数组
                tableList: [],
                // 选中的表
                tableName: "",
                // 数据条数
                limit: 1000,
                // 库数组
                dbList: [],
                // 选择的库
                dbName: "",
                // 同步数据的操作类型
                operateTypeList: [{label: "表同步", value: 1}, {label: "自定义SQL", value: 2}, {label: "远程API", value: 3}],
                // 选择的类型
                operateType: 1,
                // 数据下载的表数据类型
                dowType: [{label: "字段", value: 1}, {label: "注释", value: 2}],
                // 选择的类型
                tableType: 1,
                // 数据上传按字段还是注释 隐形的字段 按照数据下载的类型来操作
                isDowType: 1,
                // 下载的自定义SQL
                dowSql: "",
                // 字段显示顺序
                fieldOrder: "",
                // 请求类型
                methodType: [{label: "POST", value: "POST"},
                    {label: "GET", value: "GET"},
                    {label: "PUT", value: "PUT"},
                    {label: "DELETE", value: "DELETE"},
                    {label: "HEAD", value: "HEAD"},
                    {label: "OPTIONS", value: "OPTIONS"},
                    {label: "PATCH", value: "PATCH"}],
                // 选择的请求类型
                method: "POST",
                // 请求地址
                apiUrl: "",
                // 测试地址： /youyaboot-admin/magical_lowcode/openapi/db30e356274741ad84b4a2b1e679315d/cs


                // 数据上传的操作类型
                uploadTypeList: [{label: "目标表", value: 1}, {label: "临时表", value: 2}, {label: "API", value: 3}],
                // 选择的上传操作类型
                uploadType: 1,
                // 数据上传的库
                uploadDb: "",
                // 数据上传的表
                uploadTb: "",
                // 数据上传的字段
                uploadFild: "",
                // 数据上传的自定义SQL
                uploadSql: "",
                // 数据上传 api模式 请求类型
                uploadApiMethod: "POST",
                // 数据上传 api模式 请求地址
                uploadApiUrl: "",
                // 选择字段模式的字段数组
                fildList: [],
                // 选择的字段 可多选
                filds: [],
                // 临时表名称
                tmpName: "",
                // url传参参数
                query: {},
                // 样式额外存储开关
                styleSwitch: "-1",
                // 样式存储的库
                styleDb: "",
                // 样式存储的表
                styleTable: "",
                // 表下所有的字段
                styleFields: [],
                // 关联字段
                relateField: "",
                // url能获取到的参数
                queryList: [],
                // 关联参数
                relateQuery: "",

            };
        },
        created() {
            // 当前登录用户
            this.staffCode = localStorage.getItem("staffCode");
            let searchParams = new URLSearchParams(window.location.search);

            let stringList = searchParams.toString().split('&');
            if (stringList.length > 1) {
                stringList.forEach(item => {
                    let key = item.split('=');
                    this.query[key[0]] = key[1];
                    this.queryList.push({
                        label: key[0],
                        value: key[1]
                    })
                })
            }
            let id = searchParams.get("fileId");
            if (id) {
                getDataById({id: id}).then(res => {
                    this.options = res.data.data;
                })
                this.value = parseInt(id);
            } else {
                this.getData();
            }
        },
        mounted() {
            this.$nextTick(() => {
                if (this.value) {
                    this.Rendering();
                } else {
                    this.initialization(null, null);
                }
            })
        },
        methods: {
            // 数据初始化
            initialization(data, title) {
                // 初始化 Luckysheet
                this.option.title = title ? title : "初始页-随便测试";
                this.option.data = [{
                    "name": "sheet", //工作表名称
                    "color": "", //工作表颜色
                    "index": 0, //工作表索引
                    "status": 1, //激活状态
                    "order": 0, //工作表的下标
                    "hide": 0,//是否隐藏
                    "row": 36, //行数
                    "column": 18, //列数
                    "defaultRowHeight": 30, //自定义行高
                    "defaultColWidth": 90, //自定义列宽
                    "celldata": [], //初始化使用的单元格数据
                    "config": {
                        "merge": {}, //合并单元格
                        "rowlen": {}, //表格行高
                        "columnlen": {}, //表格列宽
                        "rowhidden": {}, //隐藏行
                        "colhidden": {}, //隐藏列
                        "borderInfo": [], //边框
                        "authority": {}, //工作表保护

                    },
                    "scrollLeft": 0, //左右滚动条位置
                    "scrollTop": 315, //上下滚动条位置
                    "luckysheet_select_save": [], //选中的区域
                    "calcChain": [],//公式链
                    "isPivotTable": false,//是否数据透视表
                    "pivotTable": {},//数据透视表设置
                    "filter_select": {},//筛选范围
                    "filter": null,//筛选配置
                    "luckysheet_alternateformat_save": [], //交替颜色
                    "luckysheet_alternateformat_save_modelCustom": [], //自定义交替颜色
                    "luckysheet_conditionformat_save": {},//条件格式
                    "frozen": {}, //冻结行列配置
                    "chart": [], //图表配置
                    "zoomRatio": 1, // 缩放比例
                    "image": [], //图片
                    "showGridLines": 1, //是否显示网格线
                    "dataVerification": {}, //数据验证配置
                    "data": data
                }];
                luckysheet.create(this.option);
            },
            /**
             * 获取online_file中所有的文件
             */
            getData() {
                // 获取所有工作簿
                getOptions().then(res => {
                    this.options = res.data.data;
                });
            },
            /**
             * 文件上传保存
             * @param file 通过组件获取到的file文件
             */
            handleFileUpload(file) {
                var files = [];
                files.push(file.file);
                let name = files[0].name;
                let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length - 1];
                if (suffix !== "xlsx") {
                    this.$message.error("仅支持-.xlsx-格式的文件");
                    return;
                }
                let _this = this;
                luckyexcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
                    if (exportJson.sheets == null || exportJson.sheets.length === 0) {
                        this.$message.error("未读取到文件的任何信息！");
                        return;
                    }
                    let name = exportJson.info.name.substring(0, exportJson.info.name.length - 5);
                    luckysheet.destroy();
                    _this.option.title = name;
                    _this.option.data = exportJson.sheets;
                    luckysheet.create(_this.option);
                    _this.save(name, exportJson.sheets, 0);
                })
            },
            // 单页更新
            upSheet() {
                let workName = luckysheet.getWorkbookName();
                if (workName === "初始页-随便测试") {
                    this.$message.warning("初始页不保存哦");
                    return;
                }
                let ob = JSON.parse(JSON.stringify(luckysheet.getSheet()));
                let data = ob.data;
                delete ob.data;
                let item = {
                    id: this.value,
                    index: ob.index,
                    style: JSON.stringify(ob),
                    data: JSON.stringify(data),
                    fields: JSON.stringify(this.filds),
                    uploadType: this.uploadType,
                    uploadDb: this.uploadDb,
                    uploadTb: this.uploadTb,
                    updateSql: this.uploadSql,
                    temporaryDb: this.tmpName,
                    fieldOrder: this.fieldOrder,
                    workName: workName,
                    operateType: this.operateType,
                    sheetDb: this.dbName,
                    sheetTb: this.tableName,
                    dataType: this.tableType,
                    sheetSql: this.dowSql,
                    styleSwitch: this.styleSwitch,
                    styleDb: this.styleDb,
                    styleTable: this.styleTable,
                    relateField: this.relateField,
                    relateQuery: this.relateQuery,
                    method: this.method,
                    apiUrl: this.apiUrl,
                    uploadApiMethod: this.uploadApiMethod,
                    uploadApiUrl: this.uploadApiUrl
                }
                upSheetOne(item).then(res => {
                    this.$message.success("保存成功");
                    this.getData();
                })
            },

            // 数据上传后的更新
            upSheetByfeek() {
                let workName = luckysheet.getWorkbookName();
                if (workName === "初始页-随便测试") {
                    this.$message.warning("初始页不保存哦");
                    return;
                }
                let ob = JSON.parse(JSON.stringify(luckysheet.getSheet()));
                let data = ob.data;
                delete ob.data;
                let item = {
                    id: this.value,
                    index: ob.index,
                    style: JSON.stringify(ob),
                    data: JSON.stringify(data),
                    fields: JSON.stringify(this.filds),
                    uploadType: this.uploadType,
                    uploadDb: this.uploadDb,
                    uploadTb: this.uploadTb,
                    updateSql: this.uploadSql,
                    temporaryDb: this.tmpName,
                    fieldOrder: this.fieldOrder,
                    workName: workName,
                    operateType: this.operateType,
                    sheetDb: this.dbName,
                    sheetTb: this.tableName,
                    dataType: this.tableType,
                    sheetSql: this.dowSql,
                    styleSwitch: this.styleSwitch,
                    styleDb: this.styleDb,
                    styleTable: this.styleTable,
                    relateField: this.relateField,
                    relateQuery: this.relateQuery,
                    method: this.method,
                    apiUrl: this.apiUrl,
                    uploadApiMethod: this.uploadApiMethod,
                    uploadApiUrl: this.uploadApiUrl
                }
                // 更新online_item表
                upSheetOne(item);

                // 如果开启了样式额外存储
                if (this.styleSwitch === "1") {
                    // 根据配置信息将样式存储过去
                    let item = {
                        style: JSON.stringify(ob),
                        data: JSON.stringify(data),
                        styleDb: this.styleDb,
                        table: this.styleTable,
                        field: this.relateField,
                        query: JSON.parse(JSON.stringify(this.queryList)).filter(query => query.label === this.relateQuery)[0].value
                    }
                    // 存储
                    saveStyleByQuery(item);
                }

                // 工作日历的样式单独存储
                // if (this.value === 12) {
                //     let item = {
                //         id: this.query.projectId,
                //         style: JSON.stringify(ob),
                //         data: JSON.stringify(data)
                //     }
                //     setProjectStyleById(item);
                // }

            },

            // 整表更新
            upWork() {
                let workName = luckysheet.getWorkbookName();
                if (workName === "初始页-随便测试") {
                    this.$message.warning("初始页不保存哦");
                    return;
                }
                let data = JSON.parse(JSON.stringify(luckysheet.getLuckysheetfile()));
                let ob = {
                    id: this.value,
                    workName: luckysheet.getWorkbookName(),
                    data: JSON.stringify(data)
                }
                upWorkTotal(ob).then(res => {
                    this.$message.success("保存成功");
                    this.getData();
                })
            },
            // 返回默认
            clear() {
                luckysheet.destroy();
                this.initialization(null, null);
            },
            // excale切换数据渲染
            Rendering() {
                if (!this.value) {
                    this.operateType = 1;
                    this.dbName = "";
                    this.tableName = "";
                    this.dowSql = "";
                    this.fieldOrder = "";
                    this.tableType = "";
                    this.uploadDb = "";
                    this.uploadTb = "";
                    this.uploadSql = "";
                    this.tmpName = "";
                    this.filds = [];
                    return;
                }
                let _this = this;
                let ob = {};
                this.options.forEach(item => {
                    if (item.value === _this.value) {
                        ob = item;
                    }
                });
                getOnlineFileItemByid({onlineFildId: this.value}).then(res => {
                    let data = [];
                    res.data.data.forEach(el => {
                        let item = JSON.parse(el.sheetStyle);
                        item['data'] = el.sheetData ? JSON.parse(el.sheetData) : "";
                        if (el.saveType === 1) {
                            this.operateType = el.operateType;
                            this.uploadType = el.uploadType;
                            this.filds = JSON.parse(el.uploadField)

                            this.dbName = el.sheetDb;
                            this.tableName = el.sheetTb;
                            this.tableType = el.dataType;
                            this.dowSql = el.sheetSql;
                            this.fieldOrder = el.fieldOrder;
                            this.uploadDb = el.uploadDb;
                            this.uploadTb = el.uploadTb;
                            this.uploadSql = el.updateSql;
                            this.tmpName = el.temporaryDb;
                            this.styleSwitch = el.isExtraStyle;
                            this.method = el.method;
                            this.apiUrl = el.apiUrl;
                            if (el.isExtraStyle === "1") {
                                this.styleDb = el.styleDb;
                                this.styleTable = el.styleTable;
                                this.relateField = el.relateField;
                                this.relateQuery = el.relateQuery;
                            }
                            this.uploadApiMethod = el.uploadApiMethod;
                            this.uploadApiUrl = el.uploadApiUrl;

                            // if (el.operateType === 1) {
                            //     this.dbName = el.sheetDb;
                            //     this.tableName = el.sheetTb;
                            //     this.tableType = el.dataType;
                            // } else {
                            //     this.dowSql = el.sheetSql;
                            // }
                            // if (el.uploadType === 1) {
                            //     this.uploadDb = el.uploadDb;
                            //     this.uploadTb = el.uploadTb;
                            //     this.uploadSql = el.updateSql;
                            // } else {
                            //     this.uploadSql = el.updateSql;
                            // }
                        } else {
                            this.dbName = "";
                            this.tableName = "";
                            this.dowSql = "";
                            this.fieldOrder = "";
                            this.tableType = "";
                            this.uploadDb = "";
                            this.uploadTb = "";
                            this.uploadSql = "";
                            this.tmpName = "";
                            this.filds = [];
                        }
                        data.push(item);
                    })
                    if (this.operateType === 1) {
                        luckysheet.destroy();
                        this.option.title = ob.label;
                        this.option.data = data;
                        luckysheet.create(this.option);
                    } else {
                        this.getTableDataToLucksheet();
                    }
                })
            },
            /**
             * 文件保存到数据库
             * @param fileName 文件名称
             * @param data     文件数据
             * @param type     存储类型 0：直接存储 1：数据库存储
             */
            save(fileName, data, type) {
                let ob = {
                    name: fileName,
                    data: JSON.stringify(data),
                    type: type,
                    staffCode: this.staffCode
                }
                if (type === 1) {
                    ob['operateType'] = this.operateType;
                    ob['uploadType'] = this.uploadType;
                    ob['uploadField'] = JSON.stringify(this.filds);
                    ob['isExtraStyle'] = this.styleSwitch;
                    if (this.operateType === 1) {
                        ob['sheetDb'] = this.dbName;
                        ob['sheetTb'] = this.tableName;
                        ob['dataType'] = this.tableType;
                    } else if (this.operateType === 2) {
                        ob['sheetSql'] = this.dowSql;
                    } else if (this.operateType === 3) {
                        ob['method'] = this.method;
                        ob['apiUrl'] = this.apiUrl;
                    }
                    if (this.uploadType === 1) {
                        ob['uploadDb'] = this.uploadDb;
                        ob['uploadTb'] = this.uploadTb;
                        ob['uploadSql'] = this.uploadSql;
                    } else {
                        ob['uploadSql'] = this.uploadSql;
                    }
                    if (this.styleSwitch === "1") {
                        ob['styleDb'] = this.styleDb;
                        ob['styleTable'] = this.styleTable;
                        ob['relateField'] = this.relateField;
                        ob['relateQuery'] = this.relateQuery;
                    }
                }
                saveFile(ob).then(res => {
                    if (res.data.flag) {
                        this.$message.success("上传成功");
                        let item = res.data.data;
                        this.options.push({
                            value: item.id,
                            label: item.name,
                        })
                        this.value = item.id;
                    } else {
                        luckysheet.destroy();
                        if (this.tableName === "") {
                            this.initialization(null, null);
                        }
                        this.$message.error("上传失败，请重新上传");
                    }
                })

            },
            // 导出
            exportFile() {
                let workName = luckysheet.getWorkbookName();
                if (workName === "初始页-随便测试") {
                    this.$message.warning("初始页不做操作哦");
                    return;
                }
                let data = luckysheet.getLuckysheetfile();
                luckyexcel.transformLuckyToExcel(data, workName, function () {
                    this.$message.success("导出成功")
                })
                // exportExcel(data,workName);
            },
            // 打开选择数据表弹窗并加载库数组
            openTables() {
                this.getDbs();
                // this.getTables(this.dbName);
                this.dialog1 = true;
            },
            // 库数据
            getDbs() {
                getLocalHostDB().then(res => {
                    this.dbList = res.data.data;
                })
            },
            // 选完库后加载对应表数据
            getTables(dbName) {
                getTableList(dbName).then(res => {
                    this.tableList = res.data.data;
                })
            },
            // 1弹窗关闭清空数据
            handleClose1() {
                // this.operateType = "";
                // this.dbName = "";
                // this.tableName = '';
                // this.dowSql = "";
                // this.limit = 10000;
                this.dialog1 = false;
            },
            // dialog2的打开
            openUpload() {
                let workName = luckysheet.getWorkbookName();
                if (workName === "初始页-随便测试") {
                    this.$message.warning("初始页不做操作哦");
                    return;
                }
                this.getDbs();
                // 判断是否是整表下拉 如果是 那上传库和上传表是有值的 如果不是 按照选库再选表的方式来
                if (this.uploadDb !== "") {
                    // 加载表
                    this.getTables(this.uploadDb);
                }
                // 加载字段
                this.getFild();
                this.dialog2 = true;
            },
            // uploadType === 2 选择字段模式 获取当前工作表中第一行的字段名
            getFild() {
                this.fildList = [];
                let _this = this;
                let lucksheetData = luckysheet.getSheet().data;
                // 获取表字段
                // 抽取表字段每一个单元格的具体内容
                lucksheetData[0].forEach(co => {
                    if (co && 'm' in co) {
                        let item = {
                            label: co.m
                        }
                        _this.fildList.push(item);
                    }
                })
            },
            // 2弹窗关闭
            handleClose2() {
                // this.uploadType = "";
                // this.uploadDb = "";
                // this.uploadTb = "";
                // this.uploadSql = "";
                // this.filds = [];
                this.dialog2 = false;
            },
            /**弹窗确定
             * 获取表数据 并处理数据格式为lucksheet格式
             */
            getTableDataToLucksheet() {
                if (this.operateType === "") {
                    this.$message.error("请选择操作类型");
                    return;
                } else if (this.operateType === 1) {
                    if (this.dbName === "") {
                        this.$message.error("表同步模式，请选择数据库");
                        return;
                    } else if (this.tableName === "") {
                        this.$message.error("表同步模式，请选择数据表");
                        return;
                    }
                } else if (this.operateType === 2) {
                    if (this.dowSql === "") {
                        this.$message.error("自定义SQL模式，请编写查询SQL");
                        return;
                    }
                } else if (this.operateType === 3) {
                    if (this.method === "") {
                        this.$message.error("API模式，请选择请求类型");
                        return;
                    } else if (this.apiUrl === "") {
                        this.$message.error("API模式，请填写请求地址");
                        return;
                    }
                }
                let res = {};
                // 模式1 拉表数据
                if (this.operateType === 1) {
                    // 全表下载模式 将表名赋值给上传的表名 上传的方式是直接上传 就往这个表直接插入数据了
                    this.uploadDb = this.dbName;
                    this.uploadTb = this.tableName;
                    this.isDowType = this.tableType;
                    let object = {
                        name: this.tableName,
                        dbName: this.dbName,
                        tableType: this.tableType,
                        limit: this.limit
                    };
                    getTableDataByType1(object).then(el => {
                        if (el.data.data) {
                            let ob = {
                                keys: el.data.data.keys,
                                data: el.data.data.data
                            }
                            this.dataToLuckysheet(ob);
                        } else {
                            this.$message.error("未找到数据");
                        }
                    })
                } else if (this.operateType === 2) {
                    // 模式2 自定义SQL
                    let sql = this.dowSql.replace(/\n/g, " ");
                    getTableDataByType2({dowSql: sql, query: this.query, fieldOrder: this.fieldOrder}).then(el => {
                        if (el.data.flag) {
                            if (el.data.data) {
                                let ob = {
                                    keys: el.data.data.keys,
                                    data: el.data.data.data
                                }
                                this.dataToLuckysheet1(ob);
                            } else {
                                this.$message.error("未找到数据");
                                this.initialization(null, null);
                            }
                        } else {
                            this.$message.error(el.data.desc);
                        }

                    })
                } else if (this.operateType === 3) {
                    // 模式三 api方式拉数据
                    getDataByApiUrl(this.method, this.apiUrl, this.query).then(res => {
                        if (res.data.flag) {
                            if (res.data.data) {
                                console.log(res.data.data);
                                let ob = {
                                    keys: Object.keys(res.data.data[0]),
                                    data: res.data.data
                                }
                                this.dataToLuckysheet1(ob);
                            } else {
                                this.$message.error("接口没有数据返回");
                                this.initialization(null, null);
                            }
                        } else {
                            this.$message.error(res.data.desc);
                        }
                    })
                }
                this.dialog1 = false;
            },
            /**
             * 将数据转换为luckysheet并展示
             * @param res
             */
            dataToLuckysheet(res) {
                console.log(res);
                let columns = res.keys;
                let data = res.data;
                let lucksheetData = [];
                // 拉字段
                if (this.tableType === 1) {
                    lucksheetData = dataToLucksheetModel1(columns, data);
                } else {
                    // 拉注释
                    let tableData = dataToDataByComment(columns, data);
                    // 再转换为luckysheet数据
                    lucksheetData = dataToLucksheetModel1(tableData.keys, tableData.data);
                }
                // 检测文档表中是否已存在该表
                let result = this.options.some(obj => obj.label === this.tableName);
                if (result) {
                    // 查询对应样式
                    let _this = this;
                    let ob = {};
                    this.options.forEach(item => {
                        if (item.label === _this.tableName) {
                            ob = item;
                        }
                    });
                    this.value = ob.value;
                    getOnlineFileItem({onlineFildId: ob.value}).then(res => {
                        let data = [];
                        res.data.data.forEach(el => {
                            let item = JSON.parse(el.sheetStyle);
                            item['data'] = datatoLucksheetModel2(lucksheetData, el.sheetData);
                            data.push(item);
                        })
                        luckysheet.destroy();
                        this.option.title = ob.label;
                        this.option.data = data;
                        luckysheet.create(this.option);
                    })
                } else {
                    this.value = ""
                    // 加载默认样式
                    this.initialization(lucksheetData, this.tableName);
                }
            },
            /**
             * 将数据转换为luckysheet并展示 自定义sql模式
             * @param res
             */
            dataToLuckysheet1(res) {
                let columns = res.keys;
                let data = res.data;
                let lucksheetData = dataToLucksheetModel1(columns, data);
                // 检测文档表中是否已存在该表
                if (this.value) {
                    // 查询对应样式
                    let _this = this;
                    let ob = {};
                    this.options.forEach(item => {
                        if (item.value === _this.value) {
                            ob = item;
                        }
                    });
                    // 样式额外存储过 根据配置信息从存储过的地方获取样式
                    if (this.styleSwitch === "1") {
                        this.getOnlineFileItemByQuery(lucksheetData, ob.label);
                    } else {
                        this.getOnlineFileItemStyle(lucksheetData, ob.label);
                    }
                } else {
                    this.value = ""
                    // 加载默认样式
                    this.initialization(lucksheetData, null);
                }
            },

            // 正常获取样式
            getOnlineFileItemStyle(lucksheetData, label) {
                getOnlineFileItem({onlineFildId: this.value}).then(res => {
                    let data = [];
                    res.data.data.forEach(el => {
                        let item = JSON.parse(el.sheetStyle);
                        item['data'] = datatoLucksheetModel2(lucksheetData, el.sheetData);
                        // item['data'] = [];
                        data.push(item);
                    })
                    luckysheet.destroy();
                    // this.initialization(data[0].data, ob.label);
                    // return;
                    this.option.title = label;
                    this.option.data = data;
                    luckysheet.create(this.option);
                })
            },

            // 工作日历专属样式和数据获取
            getOnlineFileItemByQuery(lucksheetData, label) {
                let item = {
                    styleDb: this.styleDb,
                    table: this.styleTable,
                    field: this.relateField,
                    query: JSON.parse(JSON.stringify(this.queryList)).filter(query => query.label === this.relateQuery)[0].value
                }
                getStyleByQuery(item).then(res => {
                    let ob = res.data.data;
                    // return;
                    if (ob && "sheetStyle" in ob) {
                        let item = JSON.parse(ob.sheetStyle);
                        item['data'] = datatoLucksheetModel2(lucksheetData, ob.sheetData);
                        luckysheet.destroy();
                        this.option.title = label;
                        this.option.data = [item];
                        luckysheet.create(this.option);
                    } else {
                        this.getOnlineFileItemStyle(lucksheetData, label);
                    }
                })
            },

            /**
             * 尝试使用luckysheet自带的api处理表格
             * @param res
             */
            async dataToLuckysheet3(res) {
                let columns = res.data.data.keys;
                let data = res.data.data.data;
                let lucksheetData = dataToLucksheetModel1(columns, data);
                // 检测文档表中是否已存在该表
                if (this.value) {
                    // 查询对应样式
                    let _this = this;
                    let ob = {};
                    this.options.forEach(item => {
                        if (item.value === _this.value) {
                            ob = item;
                        }
                    });
                    let styleData = [];
                    await getOnlineFileItem({onlineFildId: ob.value}).then(res => {
                        styleData = res.data.data;
                    })
                    let optionData = [];
                    let sheetData = [];
                    styleData.forEach(el => {
                        let item = JSON.parse(el.sheetStyle);
                        sheetData = datatoLucksheetModel2(lucksheetData, el.sheetData);
                        item['data'] = [];
                        item.cellData = [];
                        optionData.push(item);
                    })
                    // this.initialization(data[0].data, ob.label);
                    // return;
                    this.option.title = ob.label;
                    this.option.data = optionData;
                    luckysheet.create(this.option);
                    let cellData = luckysheet.getGridData(sheetData);
                    luckysheet.insertRow(36, {number: 64});
                    cellData.forEach(cell => {
                        luckysheet.setcellvalue(cell.r, cell.c, luckysheet.flowdata(), cell.v);
                    })
                    luckysheet.refresh();
                } else {
                    this.value = ""
                    // 加载默认样式
                    this.initialization(lucksheetData, null);
                }
            },


            // 拉下来的表数据 在表格中更改或者新增了新数据，将数据反写回指定数据库
            async feedback() {
                let item = [];
                if (this.filds.length <= 0) {
                    this.$message.warning("请选择字段");
                    return;
                }
                if (this.uploadType === 1) {
                    if (this.uploadDb === "") {
                        this.$message.error("请选择上传的库");
                        return;
                    } else if (this.uploadTb === "") {
                        this.$message.error("请选择上传的表");
                        return;
                    }
                    // 如果是自定义sql下载 目标表上传 需要按注释的模式上传数据
                    if (this.operateType === 2) {
                        this.isDowType = 2;
                    }
                    // 获取表的字段和注释
                    let object = {
                        name: this.uploadTb,
                        dbName: this.uploadDb,
                        tableType: this.isDowType,
                        limit: 1
                    };
                    await getTableDataByType1(object).then(el => {
                        item = el.data.data.keys;
                    })
                } else if (this.uploadType === 2) {
                    if (this.uploadSql === "") {
                        this.$message.error("请编写上传的SQL")
                        return;
                    }
                } else if (this.uploadType === 3) {
                    if (this.uploadApiMethod === "") {
                        this.$message.error("API模式，请选择请求类型");
                        return;
                    } else if (this.uploadApiUrl === "") {
                        this.$message.error("API模式，请填写请求地址");
                        return;
                    }
                }
                if (this.styleSwitch === "1") {
                    if (this.styleDb === "") {
                        this.$message.error("请选择样式上传的库");
                        return;
                    } else if (this.styleTable === "") {
                        this.$message.error("请选择样式上传的表");
                        return;
                    } else if (this.relateField === "") {
                        this.$message.error("请选择样式上传关联的表字段");
                        return;
                    } else if (this.relateQuery === "") {
                        this.$message.error("请选择样式上传关联的字段参数");
                        return;
                    }
                }
                // 工作表名称
                let workName = luckysheet.getWorkbookName();
                // 工作表数据
                let lucksheetData = JSON.parse(JSON.stringify(luckysheet.getSheet().data));

                // 存储
                // 检测文档表中是否已存在该表
                let result = this.options.some(obj => obj.label === workName);
                if (result) {
                    // 更新
                    await this.upSheetByfeek();
                } else {
                    // 表信息存储到online_file
                    await this.save(workName, luckysheet.getAllSheets(), 1);
                }

                // 数据转换
                let data = lucksheetToDataModelOne(lucksheetData);
                // 上传选择的字段 所以对data做处理
                let a = false;
                let _this = this;
                this.fildList.forEach(item => {
                    if (_this.filds.indexOf(item.label) === -1) {
                        // 说明不是全字段上传
                        a = true;
                    }
                })
                if (a) {
                    data = lucksheetToDataModelTwo(data, this.filds);
                }

                let res;
                if (this.uploadType === 1) {
                    // 下拉的注释 所以还得转字段一次
                    if (this.isDowType === 2) {
                        data = luckysheetToDataModelThree(data, item);
                    }
                    let backData = {
                        dbName: this.uploadDb,
                        name: this.uploadTb,
                        data: JSON.stringify(data),
                    }
                    if (this.uploadSql !== "") {
                        backData['sql'] = this.uploadSql.split(';');
                    }
                    // 目标表
                    await dataFeedback(backData).then(e => {
                        res = e;
                    })
                } else if (this.uploadType === 2) {
                    let sqlItem = {
                        dbName: this.tmpName,
                        sql: this.uploadSql.split(';'),
                        data: data
                    }
                    // 临时表
                    await sqlFeedback(sqlItem).then(s => {
                        res = s;
                    })
                } else if (this.uploadType === 3) {
                    // api
                    await uploadByApi(this.uploadApiMethod, this.uploadApiUrl, data).then(u => {
                        res = u;
                    })
                }
                if (res.data.flag) {
                    this.$message.success("上传成功");
                    this.getTableDataToLucksheet();
                    this.dialog2 = false;
                } else {
                    console.log("数据上传报错信息---" + res.data.desc);
                    this.$message.error("上传失败,请在控制台查看报错信息");
                }
            },
            // 字段选择框全选
            setAll() {
                let _this = this;
                this.fildList.forEach(item => {
                    if (_this.filds.length <= 0) {
                        _this.filds.push(item.label);
                    } else {
                        if (_this.filds.indexOf(item.label) === -1) {
                            _this.filds.push(item.label);
                        }
                    }
                })
            },
            // 临时表赋值
            setTmpName() {
                if (this.uploadType === 2) {
                    this.tmpName = luckysheet.getWorkbookName() + "_" + formatDate(new Date());
                }
            },
            // 同步表数据弹窗确定
            async upDialog1() {
                if (this.operateType === "") {
                    this.$message.error("请选择操作类型");
                    return;
                } else if (this.operateType === 1) {
                    if (this.dbName === "") {
                        this.$message.error("表同步模式，请选择数据库");
                        return;
                    } else if (this.tableName === "") {
                        this.$message.error("表同步模式，请选择数据表");
                        return;
                    }
                } else if (this.operateType === 2) {
                    if (this.dowSql === "") {
                        this.$message.error("自定义SQL模式，请编写查询SQL");
                        return;
                    }
                } else if (this.operateType === 3) {
                    if (this.apiUrl === "") {
                        this.$message.error("API模式，请填写请求地址");
                        return;
                    }
                }
                await this.getTableDataToLucksheet();
                setTimeout(() => {
                    this.upSheet();
                }, 1000)
                this.dialog1 = false;
            },
            // 获取某个表所有的字段
            getFieldsByTable() {
                let body =
                    {
                        "name": this.styleTable,
                        "dbName": this.styleDb,
                        "tableType": 1,
                        "limit": 1
                    }
                getTableDataByType1(body).then(res => {
                    let ob = res.data.data;
                    ob.keys.forEach(k => {
                        this.styleFields.push({
                            label: k,
                            value: k
                        })
                    })
                })
            },
            ceshi() {
                console.log(luckysheet.getAllSheets());
            }
        }
    }
</script>
<style scoped>
    @import '~spectrum-colorpicker/spectrum.css';
    @import './plugins/plugins.css';
    @import './css/luckysheet.css';
    @import './assets/iconfont/iconfont.css';
    @import './plugins/css/pluginsCss.css';

    /*.el-form-item >>> .el-form-item__content {*/
    /*    margin-left: 100px;*/
    /*    display: flex;*/
    /*}*/
</style>
